package business

import (
    "fcs-api/src/app/model"
    "time"

    "git.inspur.com/x/iam-adapter-go/resource"
)

func GetMetric(query *model.MetricQuery) ([]*model.MetricResult, error) {
    metricResultList, err := model.GetMetricQuery(query)
    if err != nil {
        _ = logger.Error("GetMetric: query db error, %v", metricResultList)
        return []*model.MetricResult{}, err
    }
    if len(metricResultList) == 0 {
        metricResultList = addZeroData(query, metricResultList)
    }
    return metricResultList, nil
}

func GetRegionMetric(user *resource.User) (*model.RegionMetricResult, error) {
    result := new(model.RegionMetricResult)
    query := &model.FunctionListQuery{
        Creator:   user.Id,
        AccountId: user.AccountId,
    }
    gp, err := model.GetGroupList(user, 1, 10, "")
    if err != nil {
        _ = logger.Error("GetMetric: query group count db error, %v", err)
        return new(model.RegionMetricResult), err
    }
    funcList, err := model.GetFuncInfoListByGroup(query)
    if err != nil {
        _ = logger.Error("GetMetric: query func count db error, %v", err)
        return new(model.RegionMetricResult), err
    }
    invokeCount, invokeComputePower, err := model.GetInvokeMonthData(user.Id)
    if err != nil {
        _ = logger.Error("GetMetric: query invoke count db error, %v", err)
        return new(model.RegionMetricResult), err
    }
    result.GroupCount = gp.TotalCount
    result.FunctionCount = int64(len(funcList))
    result.InvokeCount = invokeCount
    result.ComputePower = invokeComputePower
    return result, nil
}

func GetRegionMetricFunction(user *resource.User) (*model.RegionMetricFunctionResult, error) {
    result := new(model.RegionMetricFunctionResult)
    query := &model.FunctionListQuery{
        Creator:   user.Id,
        AccountId: user.AccountId,
    }
    funcList, err := model.GetFuncInfoListByGroup(query)
    if err != nil {
        _ = logger.Error("GetMetric: query func count db error, %v", err)
        return new(model.RegionMetricFunctionResult), err
    }
    result.FunctionCount = int64(len(funcList))
    return result, nil
}

func addZeroData(query *model.MetricQuery, rawData []*model.MetricResult) []*model.MetricResult {
    startTime := time.Unix(query.StartTime, 0)
    endTime := time.Unix(query.EndTime, 0)
    var result []*model.MetricResult
    rawIndex := 0
    for curTime := startTime; !curTime.After(endTime); curTime = curTime.Add(time.Duration(query.Period) * time.Minute) {
        metricResult := new(model.MetricResult)
        metricResult.Time = curTime
        if rawIndex < len(rawData) && !curTime.Before(rawData[rawIndex].Time) {
            metricResult.Data = rawData[rawIndex].Data
            rawIndex++
        } else {
            metricResult.Data = 0
        }
        result = append(result, metricResult)
    }
    return result
}
